
let {mat4} = require('gl-matrix');

let tmpMvMat = mat4.create();

// 创建一个多个Instance的东西
class InstanceItem{
    constructor(shaderInfo,data){

        this.count = 10;
        this.offsetPositions = [];
        const Size = 10;
        for (let i = 0; i < this.count; ++i){
            let z = -3 * Size + i * 3;
            for (let j = 0;j < this.count; ++j){
                let y = -10 + Math.random() * 5;
                let x = -Size + j * 4;
                this.offsetPositions.push(x,y,z);
                // console.log(`x:${x},y:${y},z:${z}`);
            }
        }

        let gl = window.gl;
        this.shaderInfo = shaderInfo;

        // vao
        let vao = this.vao = gl.createVertexArrayOES();
        gl.bindVertexArrayOES(vao);

        // posVBO
        let posVBO = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, posVBO);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(data.positions),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(shaderInfo.attribs['a_position']);
        gl.vertexAttribPointer(shaderInfo.attribs['a_position'],3,gl.FLOAT,false,0,0);

        // offsetVBO
        let offsetVBO = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,offsetVBO);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(this.offsetPositions),gl.STATIC_DRAW);
        gl.enableVertexAttribArray(shaderInfo.attribs['a_offsetPos']);
        gl.vertexAttribPointer(shaderInfo.attribs['a_offsetPos'],3,gl.FLOAT,false,0,0);
        gl.vertexAttribDivisorANGLE(shaderInfo.attribs['a_offsetPos'],1);

        let indiceVBO = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,indiceVBO);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,new Uint16Array(data.indices),gl.STATIC_DRAW);
        this.drawVertexCount = data.indices.length;
        gl.bindVertexArrayOES(null);

        //-----------------------------------
        // 包含基本的 T R S
        this.transMat = mat4.create();
        this.rotateMat = mat4.create();
        this.scaleMat = mat4.create();

        this.worldMatrix = mat4.create();
    }

    render(camera){
        let gl = window.gl;
        let shaderInfo = this.shaderInfo;
        gl.useProgram(shaderInfo.program);

        gl.uniformMatrix4fv(shaderInfo.uniforms['projMatrix'],false,camera.projMatrix);

        mat4.mul(this.worldMatrix,this.transMat,this.rotateMat);
        mat4.mul(this.worldMatrix,this.worldMatrix,this.scaleMat);
        mat4.mul(tmpMvMat,camera.viewMatrix,this.worldMatrix);

        gl.uniformMatrix4fv(shaderInfo.uniforms['mvMatrix'],false,tmpMvMat);

        gl.bindVertexArrayOES(this.vao);
        gl.drawElementsInstancedANGLE(gl.TRIANGLES,this.drawVertexCount,gl.UNSIGNED_SHORT,0,this.count * this.count);
        // gl.drawElements(gl.TRIANGLES,this.drawVertexCount,gl.UNSIGNED_SHORT,0);

        gl.bindVertexArrayOES(null);
        gl.useProgram(null);
    }
}


module.exports = InstanceItem;
